package cn.cj.erp.common.security.security.service;

import cn.cj.erp.bo.system.SysUserBo;
import cn.cj.erp.common.enums.StatusEnum;
import cn.cj.erp.common.exception.ServiceException;
import cn.cj.erp.common.security.security.asyncjob.AsyncFactory;
import cn.cj.erp.common.security.security.context.AuthenticationContextHolder;
import cn.cj.erp.common.security.security.user.LoginUser;
import cn.cj.erp.common.threadpool.AsyncManager;
import cn.cj.erp.common.utils.ServletUtils;
import cn.cj.erp.service.system.SysUserService;
import cn.hutool.extra.servlet.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;

/**
 * 登录校验方法
 */
@Slf4j
@Service
public class SecurityLoginService {
    @Resource
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private SysUserService sysUserService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public String login(String username, String password) {
        // 用户验证
        Authentication authentication;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.getInstance().execute(AsyncFactory.saveLoginLog(username, StatusEnum.ABNORMAL, "密码不正确"));
                throw new ServiceException("密码不正确");
            } else {
                AsyncManager.getInstance().execute(AsyncFactory.saveLoginLog(username, StatusEnum.ABNORMAL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.getInstance().execute(AsyncFactory.saveLoginLog(username, StatusEnum.NORMAL, "登录成功"));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        saveUserLogin(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 更新用户登录信息
     *
     * @param userId 用户ID
     */
    public void saveUserLogin(Long userId) {
        SysUserBo user = new SysUserBo();
        user.setUserId(userId);
        user.setLoginIp(ServletUtil.getClientIP(ServletUtils.getRequest()));
        user.setLoginTime(new Date());
        if (!sysUserService.updateLogin(user)) {
            log.error("更新登录信息失败, user = {}", userId);
            throw new ServiceException("更新登录信息失败");
        }
    }
}
